#include "VTKSamplePointCloud.h"
#include <vtkActor.h>
#include <vtkCleanPolyData.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPointSource.h>
#include <vtkPolyData.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>

VTKSamplePointCloud::VTKSamplePointCloud(QWidget *parent)
    : QMainWindow(parent)
{
	vtkWidget = new QVTKOpenGLNativeWidget(this);
	this->resize(600, 400);
	this->setCentralWidget(vtkWidget);

	vtkNew<vtkNamedColors> colors;

	vtkNew<vtkPointSource> pointSource;
	pointSource->SetNumberOfPoints(10000);
	pointSource->Update();
	auto pts = pointSource->GetNumberOfPoints();

	vtkNew<vtkCleanPolyData> cleanPolyData;
	cleanPolyData->SetInputConnection(pointSource->GetOutputPort());
	
	cleanPolyData->SetTolerance(1);
	cleanPolyData->Update();
	auto cleanPts = cleanPolyData->GetOutput()->GetNumberOfPoints();

	std::cout << "Original points" << pts << std::endl;
	std::cout << "Cleaned points " << cleanPts << std::endl;
	std::cout << "Reduction      "
		<< (1.0 - static_cast<double>(cleanPts) / pts) * 100.0 << "%"
		<< std::endl;

	vtkNew<vtkPolyDataMapper> inputMapper;
	inputMapper->SetInputConnection(pointSource->GetOutputPort());
	vtkNew<vtkActor> inputActor;
	inputActor->SetMapper(inputMapper);
	inputActor->GetProperty()->SetColor(colors->GetColor3d("Lime").GetData());
	inputActor->GetProperty()->SetPointSize(3);

	vtkNew<vtkPolyDataMapper> cleanedMapper;
	cleanedMapper->SetInputConnection(cleanPolyData->GetOutputPort());
	vtkNew<vtkActor> cleanedActor;
	cleanedActor->SetMapper(cleanedMapper);
	cleanedActor->GetProperty()->SetColor(colors->GetColor3d("Lime").GetData());
	cleanedActor->GetProperty()->SetPointSize(3);	

	// Setup both renderers
	vtkNew<vtkRenderer> leftRenderer;
	vtkWidget->renderWindow()->AddRenderer(leftRenderer);
	leftRenderer->SetBackground(colors->GetColor3d("van_dyke_brown").GetData());

	leftRenderer->AddActor(inputActor);

	leftRenderer->ResetCamera();
}

VTKSamplePointCloud::~VTKSamplePointCloud()
{
	vtkWidget->interactor()->SetRenderWindow(nullptr);
	vtkWidget->interactor()->SetInteractorStyle(nullptr);
}
